package club.ruanx.spider.controller;

import club.ruanx.redis.entity.MessageData;
import club.ruanx.spider.async.AsyncSpider;
import club.ruanx.spider.common.message.SpiderMessageClient;
import club.ruanx.spider.entity.SpiderMovie;
import club.ruanx.spider.service.SpiderMovieService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 阮胜
 * @date 2018/11/12 22:35
 */
@RestController
@RequestMapping("/spider")
@Slf4j
public class SpiderMovieController {
    private final SpiderMovieService spiderMovieService;
    private final AsyncSpider asyncSpider;

    @Autowired
    private SpiderMessageClient spiderMessageClient;

    public SpiderMovieController(SpiderMovieService spiderMovieService, AsyncSpider asyncSpider) {
        this.spiderMovieService = spiderMovieService;
        this.asyncSpider = asyncSpider;
    }


    @PostMapping("/save")
    public SpiderMovie save(@RequestBody SpiderMovie spiderMovie) {
        log.debug(spiderMovie.toString());
        return spiderMovieService.save(spiderMovie);
    }

    @GetMapping("/douban/start")
    public void startDouban(@RequestParam(defaultValue = "热门") String type, @RequestParam(defaultValue = "10") int limit,
                            @RequestParam(defaultValue = "0") int pageStart) throws IOException {
        log.info("开始执行豆瓣爬虫,类型:{},数量:{}", type, limit);
        asyncSpider.startDoubanSpider(type, limit, pageStart);
    }

    @GetMapping("/douban/fetch")
    public void fetchByIds(String[] id) {
        Set<String> idSet = Stream.of(id).collect(Collectors.toSet());
        asyncSpider.startWithIdSet(idSet);
    }

    @PostMapping("/send/msg")
    public boolean msg(@RequestBody MessageData messageData) {
        return spiderMessageClient.input().send(MessageBuilder.withPayload(messageData).build());
    }
}
